package com.example.chenzhiran.myapplication7;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chenzhiran.myapplication7.server.clientData;
import com.example.chenzhiran.myapplication7.server.serverData;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class MainActivity extends AppCompatActivity {


    //gridview和搜索框
    private GridView mProductGridView;
    private List<ProductInfo> mProductInfos;
    public EditText mSearchEditText;

    //底部的两个按钮
    public ImageButton mSearchButton;
    private ImageButton mLikeButton;
    public String inputSearchText = null;
    clientData outdata2 = new clientData();
    String username = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("主页");

        Intent intent = getIntent();
            if(intent != null){
                username = intent.getStringExtra("username");
            }


        outdata2.pageId = 2;


        /**
         * 1 spinner的设置
         */

        Spinner heightspinner = (Spinner) findViewById(R.id.height_spinner);
        Spinner weightspinner = (Spinner) findViewById(R.id.weight_spinner);
        Spinner genderspinner = (Spinner) findViewById(R.id.gender_spinner);

        final List<String> heightdatas = new ArrayList<>();
        final List<String> weightdatas = new ArrayList<>();
        final List<String> genderdatas = new ArrayList<>();

        heightdatas.add("身高");
        for (int i = 150; i < 200; i+=5) { heightdatas.add(i + "cm"); }

        weightdatas.add("体重");
        for (int i = 30; i < 100; i+=5) { weightdatas.add(i + "kg"); }

        genderdatas.add("性别");
        genderdatas.add("男");
        genderdatas.add("女");

        MyAdapter heightadapter = new MyAdapter(this);
        MyAdapter weightadapter = new MyAdapter(this);
        MyAdapter genderadapter = new MyAdapter(this);

        heightspinner.setAdapter(heightadapter);
        weightspinner.setAdapter(weightadapter);
        genderspinner.setAdapter(genderadapter);

        heightadapter.setDatas(heightdatas);
        weightadapter.setDatas(weightdatas);
        genderadapter.setDatas(genderdatas);

        //spinner中身高的点击事件
        heightspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String heightstring = (heightdatas.get(position));
                int intheightdatas = 0;

                try{
                    intheightdatas = Integer.parseInt(heightstring.substring(0,heightstring.length()-2));

                }catch(Exception e){
                    e.printStackTrace();
                }
                outdata2.userheight = intheightdatas;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //spinner中体重的点击事件
        weightspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String weightstring = (weightdatas.get(position));

                int intweightdatas = 0;

                try{
                    intweightdatas = Integer.parseInt(weightstring.substring(0,weightstring.length()-2));

                }catch(Exception e){
                    e.printStackTrace();
                }


                outdata2.userweight = intweightdatas;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ////spinner中性别的点击事件
        genderspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String genderstring = (genderdatas.get(position));
                if(genderstring == "男"){
                    outdata2.gendere = true;
                }
                else
                    outdata2.gendere = false;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        /**
         * 2 搜索框和搜索按钮的设置
         */

        mSearchEditText = (EditText) findViewById(R.id.search_editText);
        mSearchButton = (ImageButton)this.findViewById(R.id.search_imageButton);
        mSearchButton.setOnClickListener(mOnClickListener);

        try{
            inputSearchText = mSearchEditText.getText().toString();
        }catch(Exception e){
            e.printStackTrace();
        }

        outdata2.inputmessage = inputSearchText;

        /**
         * 3 GridView
         */

        mProductGridView = (GridView) findViewById(R.id.grid_view);
        mProductInfos = new ArrayList<>();
        final GridViewAdapter productAdapter = new GridViewAdapter(MainActivity.this, mProductInfos);
        mProductGridView.setAdapter(productAdapter);



        //gridview的点击事件
        mProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, ProductActivity.class);

                RelativeLayout relativeLayout = (RelativeLayout) mProductGridView.getAdapter().getView(position, view, null);
                TextView productid= (TextView) relativeLayout.getChildAt(3);
                intent.putExtra("productid",productid.getText().toString());
                intent.putExtra("username",username);
                startActivity(intent);


            }


        });

        /**
         * 4 下拉刷新
         */
        final SwipeRefreshLayout mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.layoutest);

        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                // 开始刷新，设置当前为刷新状态
                mSwipeLayout.setRefreshing(true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        outdata2.dataId = 1;

                        //1 填写了搜索内容
                        if(hasWords(inputSearchText) == true){
                            outdata2.picpos = mProductInfos.size()+1;
                            //如果是男生
                            if(outdata2.gendere == true){
                                outdata2.category = "1";
                            }
                            //如果是女生
                            else{
                                outdata2.category = "2";

                            }

                        }
                        //2 没填写搜索内容
                        else{
                            outdata2.picpos = 0;
                            outdata2.category = "2";
                        }

                        //刷新事件
                        new MainActivity.connection().execute(outdata2);
                        productAdapter.notifyDataSetChanged();
                        Toast.makeText(MainActivity.this, "刷新了一条数据", Toast.LENGTH_SHORT).show();
                        // 加载完数据设置为不刷新状态，将下拉进度收起来
                        mSwipeLayout.setRefreshing(false);
                    }
                }, 1200);

            }
        });

        /**
         * 5 底部跳转到我的页面
         */

        mSearchButton = (ImageButton) this.findViewById(R.id.search_layout_imageButton);
        mLikeButton = (ImageButton) this.findViewById(R.id.like_layout_imageButton);

        mSearchButton.setOnClickListener(mOnClickListener);
        mLikeButton.setOnClickListener(mOnClickListener);

    }

     //设置点击事件
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.search_imageButton:
                    outdata2.dataId = 0;
                    if(hasWords(inputSearchText) == true){
                        new MainActivity.connection().execute(outdata2);
                    }
                    break;
                case R.id.search_layout_imageButton:
                    Intent intent = new Intent(MainActivity.this, PurchaseActivity.class);
                    startActivity(intent);
                    break;
                case R.id.like_layout_imageButton:
                    Intent intent1 = new Intent(MainActivity.this, MyActivity.class);
                    intent1.putExtra("username",username);
                    startActivity(intent1);
                    break;

            }
        }
    };

    //设置是否填写搜索内容
    private boolean hasWords(String inputSearchText)
    {
        if(inputSearchText == null || inputSearchText.length() == 0 )
        {
            Toast.makeText(MainActivity.this, "请输入搜索内容",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //连接
    public class connection extends AsyncTask<clientData, Void, serverData>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected serverData doInBackground(clientData... params)
        {
            clientData data = params[0];
            serverData indata = new serverData();
            try
            {
                Socket socket = new Socket("103.242.1.105", 1080);
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                out.writeObject(data);
                out.flush();
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                indata = (serverData) in.readObject();
                in.close();
                out.close();
                socket.close();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
            return indata;
        }

        //返回的商品信息
        @Override
        protected void onPostExecute(serverData data)
        {
            super.onPostExecute(data);

            //System.out.println(data.imgs.size());

            for(final String key : data.imgs.keySet())
            {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data.imgs.get(key), 0,
                        data.imgs.get(key).length);

                mProductInfos.add(new ProductInfo(data.productdescribes.get(key), data.productprices.get(key),bitmap,key));

            }

        }
    }


}
